package com.ltxtiyu.video.callBack;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ltxtiyu.video.bean.VideoInfoBean;
import com.ltxtiyu.video.cacheDao.VideoCacheDao;
import com.ltxtiyu.video.common.JsonTool;
import com.ltxtiyu.video.common.RetEnum;
import com.ltxtiyu.video.dao.ltx.VideoDao;
import com.ltxtiyu.video.entity.Video;
import com.ltxtiyu.video.tool.NumberTool;
import com.ltxtiyu.video.tool.ParamTool;
import javafx.application.Application;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.applet.Applet;
import java.applet.AppletContext;
import java.awt.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

/**
 * ali视频回调
 * 视频上传转码完成后修改数据库视频地址,是否可播放
 */
@RestController
public class AliVideoCallBack {
    public static final Logger LOGGER = LoggerFactory.getLogger(AliVideoCallBack.class);

    @Autowired
    VideoDao videoDao;
    @Autowired
    VideoCacheDao videoCacheDao;
    /**
     * ali视频回调
     * 视频上传转码完成后修改数据库视频地址,是否可播放
     * @param request
     * @return
     */
    @RequestMapping(value = "/aliVideoCallBack",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String aliVideoCallBack(HttpServletRequest request){
        LOGGER.info(">>>>>>>>>>>>开始执行ali视频回调");
        JSONObject jsonParam = getJSONParam(request);
        if(jsonParam == null){
            return JsonTool.genJson(RetEnum.SUCCESS);
        }
        if(jsonParam.get("EventType") == null){
            return JsonTool.genJson(RetEnum.SUCCESS);
        }

        String videoId = (String)jsonParam.get("VideoId");    // 视频id
        LOGGER.info(">>>>>>>>>>>>执行ali视频回调ing,返回参数:{}",jsonParam.toJSONString());

        if("TranscodeComplete".equals(jsonParam.get("EventType")) && "success".equals(jsonParam.get("Status"))){
            String fileUrl = "";                    // 视频播放地址
            String duration = "0";                  // 视频时长
            //修改视频状态
            try {
                List<JSONObject> streamInfos = (List<JSONObject>) jsonParam.get("StreamInfos");
                for(JSONObject streamInfo : streamInfos){   // 有两种格式mp4, m3u8
                    if("mp4".equals(streamInfo.get("Format"))){     // 只保存mp4格式的
                        fileUrl = String.valueOf(streamInfo.get("FileUrl"));
                        duration = (NumberTool.floatFormat(String.valueOf(streamInfo.get("Duration")), 1000)) + "";
                    }
                }
            }catch (Exception e){
                LOGGER.info(">>>>>>>>>>>>ali视频回调,获取视频url失败,videoId:{}, 错误信息:{}", videoId, e);
            }
            Video video = videoDao.selectByVideoId(videoId);
            if(video != null) {
                if (StringUtils.isNotBlank(video.getVideoInfo())) {
                    VideoInfoBean videoInfoBean = JSON.parseObject(video.getVideoInfo(), VideoInfoBean.class);
                    videoInfoBean.setPlayUrl(fileUrl);
                    videoInfoBean.setCoverUrl(videoInfoBean.getCoverUrl()); // 有可能先调了封面回调
                    videoInfoBean.setDuration(duration);
                    video.setVideoInfo(JSON.toJSONString(videoInfoBean));
                    video.setStatus(1);                                     // 设置视频状态为1, 可播放
                    videoCacheDao.updateByPrimaryKeySelective(video);
                } else {
                    VideoInfoBean videoInfoBean = new VideoInfoBean();
                    videoInfoBean.setPlayUrl(fileUrl);
                    videoInfoBean.setCoverUrl("");
                    videoInfoBean.setDuration(duration);
                    video.setVideoInfo(JSON.toJSONString(videoInfoBean));
                    videoCacheDao.updateByPrimaryKeySelective(video);
                }
            }
        }
        if("SnapshotComplete".equals(jsonParam.get("EventType")) && "success".equals(jsonParam.get("Status"))){
            String coverUrl = (String) jsonParam.get("CoverUrl");
            Video video = videoDao.selectByVideoId(videoId);
            if(video != null){
                if(StringUtils.isNotBlank(video.getVideoInfo())){
                    VideoInfoBean videoInfoBean = JSON.parseObject(video.getVideoInfo(), VideoInfoBean.class);
                    videoInfoBean.setPlayUrl(videoInfoBean.getPlayUrl()); // 有可能先调了视频回调
                    videoInfoBean.setCoverUrl(coverUrl);
                    videoInfoBean.setDuration(videoInfoBean.getDuration()); // 有可能先调了视频回调
                    video.setVideoInfo(JSON.toJSONString(videoInfoBean));
                    video.setStatus(1);                                     // 设置视频状态为1, 可播放
                    videoCacheDao.updateByPrimaryKeySelective(video);
                }else {
                    VideoInfoBean videoInfoBean = new VideoInfoBean();
                    videoInfoBean.setPlayUrl("");
                    videoInfoBean.setCoverUrl(coverUrl);
                    videoInfoBean.setDuration("0");
                    video.setVideoInfo(JSON.toJSONString(videoInfoBean));
                    videoCacheDao.updateByPrimaryKeySelective(video);
                }
            }
        }
        return JsonTool.genJson(RetEnum.SUCCESS);
    }

    /**
     * 通过request的对象来获取到输入流，然后将输入流的数据写入到字符串里面，最后转化为JSON对象
     * @param request
     * @return
     */
    public JSONObject getJSONParam(HttpServletRequest request){
        JSONObject jsonParam = null;
        try {
            // 获取输入流
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));

            // 写入数据到Stringbuilder
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = streamReader.readLine()) != null) {
                sb.append(line);
            }
            jsonParam = JSONObject.parseObject(sb.toString());
            // 直接将json信息打印出来
            System.out.println(jsonParam.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonParam;
    }
}
